package com.funmi.lizip.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.Patrol;
import com.funmi.lizip.entity.PatrolTrack;
import com.funmi.lizip.entity.Personnel;
import com.funmi.lizip.entity.User;
import com.funmi.lizip.entity.dto.personnel.PersonnelUpdateRequest;
import com.funmi.lizip.mapper.PersonnelMapper;
import com.funmi.lizip.service.PatrolService;
import com.funmi.lizip.service.PatrolTrackService;
import com.funmi.lizip.service.PersonnelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funmi.lizip.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yeyg
 * @since 2022-11-03
 */
@Service
public class PersonnelServiceImpl extends ServiceImpl<PersonnelMapper, Personnel> implements PersonnelService {

    @Autowired
    private PersonnelMapper personnelMapper;
    @Autowired
    @Lazy
    private PatrolTrackService patrolTrackService;
    @Autowired
    @Lazy
    private PatrolService patrolService;
    @Autowired
    @Lazy
    private UserService userService;

    /**
     * 根据巡护人员id，获取人员位置、轨迹、任务执行
     * @param id
     */
    @Override
    public void getDetailed(int id) {
        // 获取巡护人员信息
        Personnel personnel = personnelMapper.selectById(id);
        // 获取所选巡护人员正在执行中的任务
        List<Integer> patrolIds = patrolService.getByRangerId(id);
        if (patrolIds == null){
            return;
        }
        HashMap<Integer, Patrol> patrolHashMap = new HashMap<>();
        patrolIds.forEach(patrolId ->
        {
            Patrol patrol = patrolService.getById(patrolId);
            patrolHashMap.put(patrolId, patrol);
        });
        // 获取轨迹路线
        PatrolTrack byId = patrolTrackService.getById(id);
        // 组装返回
    }

    /**
     *
     * */
    @Override
    public boolean updateByID(HashMap<String, Object> request) {
        if (request == null){
            R.success().message("修改失败");
            return false;
        }
        Personnel personnel = JSONObject.parseObject(JSONObject.toJSONBytes(request), Personnel.class);

        /*if (request.get("otherMsg") != null && request.get("otherMsg") != "") {
            personnel.setOtherMsg(new JSONObject((Map<String, Object>) request.get("otherMsg")));
        }*/
        if (request.get("position") != null && request.get("position") != "") {
            personnel.setPosition(new JSONArray((List<Object>) request.get("position")));
        }
        if (request.get("positionJson") != null && request.get("positionJson") != "") {
            personnel.setPositionJson(new JSONObject((Map<String, Object>) request.get("positionJson")));
        }
        BeanUtils.copyProperties(request, personnel);
        // personnel.setId(id);

        int i = personnelMapper.updateById(personnel);
        if (i == 1){
            R.success().message("修改成功");
            return true;
        }
        R.success().message("修改失败");
        return false;
    }

    @Override
    public boolean deleteByID(int id) {
        if (id < 0){
            R.success().message("删除失败");
            return false;
        }
        int i = personnelMapper.deleteById(id);
        if (i == 1){
            R.success().message("删除成功");
            return true;
        }
        R.success().message("删除失败");
        return false;
    }

    @Override
    public String getNameById(Integer id) {
        Personnel personnel = personnelMapper.selectById(id);
        if (personnel==null){
            return null;
        }
        return personnel.getName();
    }

    @Override
    public void updateOtherMsg(JSONObject jsonObject) {

    }

    /**
     * 通过名字获取护林员
     * @param rangerName
     * @return
     */
    @Override
    public Personnel getByName(String rangerName) {
        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", rangerName);
        List<Personnel> personnels = personnelMapper.selectList(queryWrapper);
        if (personnels == null && personnels.size() == 0){
            return null;
        }
        if (StringUtils.isEmpty(personnels.get(0))){
            return null;
        }
        return personnels.get(0);
    }


    /**
     * 根据护林员的id，获取护林员的巡护轨迹列表，
     * @param id
     * @return
     */
    @Override
    public List<PatrolTrack> getAttendance(int id) {
        PatrolTrack patrolTrack = new PatrolTrack();
        QueryWrapper<PatrolTrack> patrolTrackQueryWrapper = new QueryWrapper<>();
        patrolTrackQueryWrapper.eq("ranger_id",id);
        List<PatrolTrack> list = patrolTrackService.list(patrolTrackQueryWrapper);
        return list;
    }

    /**
     * 新增护林员的同时 添加护林员账号
     * @param personnel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean savePersonAndUser(Personnel personnel) {
        PasswordEncoder delegatingPasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        int insert = personnelMapper.insert(personnel);
        User user = new User();
        user.setPassword(delegatingPasswordEncoder.encode("123456"));
        //userService.save()
        user.setUsername(personnel.getContactTel());
        user.setPhone(personnel.getContactTel());
        user.setLoginAt(null);
        user.setId(null);
        return userService.save(user);
    }

    /*@Override
    public void updateOtherMsg(int id; JSONObject jsonObject) {
        PersonnelMapper.updateOtherMsg();
    }*/


}
